import React, { useEffect, useState } from 'react';
import { turnoverByLeaderChildren } from '@/pages/WorkFlow/components/FormControls/formConfig/custom/turnoverLeader';
import { Form, Input } from 'antd';
import AutoRenderComponent from '@/pages/WorkFlow/components/FormControls/components/AutoRenderComponent';
import { withRouter } from 'umi';

const { Item } = Form;

const TurnoverByLeader = ({ form, dataSource, location, formValueMap = {}, ...otherProps }) => {
    const { getFieldDecorator, setFieldsValue } = form;
    const [items, setItems] = useState([]);
    const [employeeCode, setEmployeeCode] = useState(
        location?.query?.employeeCode || formValueMap.employeeName || null // 不知道之前什么逻辑了，employeeName和employeeCode应该是去name!!
    );
    const { applyType } = dataSource;
    const { organizationCode } = otherProps;

    const handleOnSelect = uInfo => {
        if (uInfo) {
            const { dutyCode, organizationName, positionName, rankValue, timeOfEntry, employeeCode: code } = uInfo;
            setFieldsValue({ organizationName, positionName, rankValue, timeOfEntry, dutyCode });
            setEmployeeCode(code);
        }
    };

    // 特殊的配置
    const OPTIONS_CONFIG = {
        employeeName: {
            defaultActiveFirstOption: false,
            showArrow: false,
            filterOption: false,
            notFoundContent: null,
            onSelect: handleOnSelect
        }
    };

    useEffect(() => {
        if (dataSource?.children.length > 0) {
            setItems(dataSource?.children);
        } else {
            setItems(turnoverByLeaderChildren);
        }
    }, [dataSource]);

    return (
        <>
            {items?.length &&
                items.map(v => {
                    const o = { ...v.options, ...OPTIONS_CONFIG[v?.formId] };
                    if (v.tag === 'ContactsInput') {
                        v.initialValue = employeeCode;
                    }
                    // applyType organizationCode 主管发起的时候需要用这两个参数
                    o.applyType = applyType;
                    o.organizationCode = organizationCode;

                    return (
                        <Item label={v.label} key={v.formId}>
                            {getFieldDecorator(v.formId, {
                                initialValue: v.initialValue,
                                rules: v.rules
                            })(<AutoRenderComponent config={v} form={form} {...o} />)}
                        </Item>
                    );
                })}
            <Item style={{ display: 'none' }}>
                {getFieldDecorator('employeeCode', {
                    initialValue: employeeCode
                })(<Input />)}
                {getFieldDecorator('dutyCode')(<Input />)}
            </Item>
        </>
    );
};

export default withRouter(TurnoverByLeader);
